package com.basic.backend.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.basic.backend.annotation.AuthCheck;
import com.basic.backend.common.BaseResponse;
import com.basic.backend.common.ErrorCode;
import com.basic.backend.common.ResultUtils;
import com.basic.backend.exception.BusinessException;
import com.basic.backend.exception.ThrowUtils;
import com.basic.backend.model.dto.analysis.ArticleAnalysisDTO;
import com.basic.backend.model.dto.articles.ArticleAddRequest;
import com.basic.backend.model.dto.articles.ArticleQueryRequest;
import com.basic.backend.model.dto.articles.ArticleUpdateRequest;
import com.basic.backend.model.entity.AnalysisResult;
import com.basic.backend.model.entity.Articles;
import com.basic.backend.model.vo.AnalysisResultVO;
import com.basic.backend.model.vo.ArticleVO;
import com.basic.backend.service.AnalysisService;
import com.basic.backend.service.ArticlesService;
import com.basic.backend.service.UserService;
import com.basic.backend.service.impl.MessageProducer;
import com.basic.backend.utils.WordParserUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 文章接口
 */
@RestController
@RequestMapping("/article")
@Api(tags = "文章管理")
@Slf4j
public class Articlecontroller {

    @Resource
    private ArticlesService articleService;

    @Resource
    private UserService userService;

    @Resource
    private MessageProducer messageProducer;

    @Resource
    private AnalysisService analysisService;


    /**
     * 创建文章
     *
     * @param request     文章请求参数
     * @param httpRequest HTTP请求上下文
     * @return 文章ID
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建文章", notes = "用户创建新文章")
    @AuthCheck(mustRole = "user")
    public BaseResponse<Long> addArticle(@RequestBody ArticleAddRequest request,
                                         HttpServletRequest httpRequest) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2. 获取当前登录用户
        Long userId = userService.getLoginUser(httpRequest).getId();
        // 3. 转换DTO到实体
        Articles article = new Articles();
        BeanUtils.copyProperties(request, article);
        article.setUserId(userId);
        // 4. 保存文章
        boolean result = articleService.saveArticle(article);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "文章创建失败");
        String token = StpUtil.createLoginSession(userId);
        if (result) {
            ArticleAnalysisDTO dto = new ArticleAnalysisDTO(
                    article.getArticleId(),
                    article.getTitle(),
                    article.getContent()

            );
            messageProducer.sendAnalysisTask(dto);
        }
        return ResultUtils.success(article.getArticleId(), token);
    }




    @GetMapping("/analysis")
    @ApiOperation(value = "获取文章分析结果", notes = "返回结构化热词列表")
    public BaseResponse<AnalysisResultVO> getAnalysisResult(
            @RequestParam  Long articleId) {

        // 参数校验
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文章ID不合法");
        }

        // 查询原始数据
        AnalysisResult entity = analysisService.getOne(
                new LambdaQueryWrapper<AnalysisResult>()
                        .eq(AnalysisResult::getArticleId, articleId)
                        .last("LIMIT 1")
        );

        if (entity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "分析结果不存在");
        }

        // 转换VO
        AnalysisResultVO vo = new AnalysisResultVO();
        BeanUtils.copyProperties(entity, vo);
        //通过文章id找到用户名
        String userName = userService.getUserVO(articleService.getById(articleId).getUserId()).getUserName();
        vo.setAuthor(userName);
        //通过文章id找到文章内容返回文章数字
        vo.setWordCount(articleService.getById(articleId).getContent().length());
        vo.setHotWords(convertHotWords(entity.getHotWords()));
        return ResultUtils.success(vo, "查询成功");
    }

    // JSON字符串转列表
    private List<AnalysisResultVO.HotWord> convertHotWords(String hotWordsJson) {
        try {
            return JSON.parseArray(hotWordsJson, AnalysisResultVO.HotWord.class);
        } catch (JSONException e) {
            log.error("热词解析失败 JSON: {}", hotWordsJson, e);
            return Collections.emptyList();
        }
    }

    @PostMapping("/page")
    @ApiOperation("文章分页查询")
    public BaseResponse<Page<ArticleVO>> getArticlePage(
            @RequestBody ArticleQueryRequest request,
            HttpServletRequest httpRequest) {

        // 权限处理：非管理员只能查自己
        Long userId = userService.getUserIdByToken(httpRequest);
        if (!userService.isAdmin(httpRequest)) {
            request.setUserId(userId);
        }
        String token = StpUtil.createLoginSession(userId);
        return ResultUtils.success(articleService.getArticlePage(request), token);
    }



    @DeleteMapping("/delete")
    @ApiOperation(value = "删除文章", notes = "根据文章ID删除文章")
    public BaseResponse<Boolean> deleteArticle(@RequestParam("id") Long articleId,
                                               HttpServletRequest request) {
        // 参数校验
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文章ID不合法");
        }

        // 获取当前登录用户
        Long userId = userService.getUserIdByToken(request);
        // 删除文章
        boolean result = articleService.removeById(articleId);
        return result ? ResultUtils.success(true, "删除成功") : ResultUtils.error(ErrorCode.OPERATION_ERROR, "删除失败");
    }


    /**
     * 获取文章详情
     * @param articleId 文章ID
     * @param request HTTP请求上下文（用于获取基地址）
     * @return 文章详情VO
     */
    @GetMapping("/info")
    @ApiOperation("获取文章详情")
    @AuthCheck(mustRole = "user") // 添加权限校验注解
    public BaseResponse<Articles> getArticleById(
            @RequestParam("id") Long articleId, // 绑定查询参数id
            HttpServletRequest request) {

        // 参数校验
        if (articleId == null || articleId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文章ID不合法");
        }

        // 获取文章详情
        Articles articleVO = articleService.getById(articleId);
        if (articleVO == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "文章不存在");
        }
        Long userId = userService.getUserIdByToken(request);
        if (!articleVO.getUserId().equals(userId)) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "无权限访问");
        }
        articleVO.setUserId(userId);
        String token = StpUtil.createLoginSession(userId);
        return ResultUtils.success(articleVO,token);
    }

    @PostMapping("/update")
    @ApiOperation("更新文章")
    @AuthCheck(mustRole = "user")
    public BaseResponse<Boolean> updateArticle(@RequestBody ArticleUpdateRequest request,
                                               HttpServletRequest httpRequest) {
        if (request == null || request.getArticleId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = userService.getUserIdByToken(httpRequest);
        Articles article = new Articles();
        BeanUtils.copyProperties(request, article);
        //更新用户id
        article.setUserId(userId);
        boolean result = articleService.updateArticle(request.getArticleId(), request, userId);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "文章更新失败");
        String token = StpUtil.createLoginSession(userId);
        if (result) {
            ArticleAnalysisDTO dto = new ArticleAnalysisDTO(
                    article.getArticleId(),
                    article.getTitle(),
                    article.getContent()
            );
            messageProducer.sendAnalysisTask(dto);
        }
        return ResultUtils.success(result, "");
    }

    @PostMapping("/deleteBatch")
    @ApiOperation("批量删除文章")
    @AuthCheck(mustRole = "user")
    public BaseResponse<Boolean> deleteBatchArticles(@RequestBody List<Long> articleIds,
                                                       HttpServletRequest request) {
        if (articleIds == null || articleIds.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请选择要删除的文章");
        }
        // 获取当前登录用户
        Long userId = userService.getUserIdByToken(request);
        // 删除文章
        boolean result = articleService.removeByIds(articleIds);
        //删除文章对应的分析结果
        for (Long articleId : articleIds) {
            QueryWrapper<AnalysisResult> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("articleId", articleId);
            analysisService.remove(queryWrapper);
        }
        return ResultUtils.success(result, "");
    }


    @PostMapping("/upload")
    @ApiOperation(value = "上传Word文件创建文章", notes = "支持批量上传Word文件")
    @AuthCheck(mustRole = "user")
    public BaseResponse<List<Long>> uploadWordFiles(
            @RequestPart("files") @ApiParam(value = "Word文件列表", required = true) MultipartFile[] files,
            HttpServletRequest httpRequest) {

        if (files == null || files.length == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请选择要上传的文件");
        }

        List<Long> articleIds = new ArrayList<>();
        Long userId = userService.getLoginUser(httpRequest).getId();

        for (MultipartFile file : files) {
            try {
                // 解析Word内容
                String content = WordParserUtil.parseWordContent(file);
                if (StringUtils.isBlank(content)) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件内容不能为空");
                }

                // 使用文件名作为标题（去除扩展名）
                String originalFilename = file.getOriginalFilename();
                String title = originalFilename.contains(".") ?
                        originalFilename.substring(0, originalFilename.lastIndexOf('.')) :
                        originalFilename;

                // 构建请求对象
                ArticleAddRequest addRequest = new ArticleAddRequest();
                addRequest.setTitle(title);
                addRequest.setContent(content);

                // 调用现有添加文章逻辑
                Articles article = new Articles();
                BeanUtils.copyProperties(addRequest, article);
                article.setUserId(userId);

                if (articleService.saveArticle(article)) {
                    articleIds.add(article.getArticleId());
                    // 发送分析任务
                    ArticleAnalysisDTO dto = new ArticleAnalysisDTO(
                            article.getArticleId(),
                            title,
                            content
                    );
                    messageProducer.sendAnalysisTask(dto);
                }
            } catch (BusinessException e) {
                log.error("文件上传失败: {}", file.getOriginalFilename(), e);
                // 继续处理其他文件
            }
        }

        if (articleIds.isEmpty()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "所有文件处理失败");
        }

        String token = StpUtil.createLoginSession(userId);
        return ResultUtils.success(articleIds, token);
    }
}
